package com.lanou3g.code0416;

import java.io.*;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/4/16;
 * Otherwise, I don't know who created it either
 */

public class Main {
    public static void main(String[] args) {
        String srcPath = "C:\\Users\\73448\\Desktop\\aaa.mp4";
        String desPath = "C:\\Users\\73448\\Desktop\\bbb.mp4";
        String desPath1 = "C:\\Users\\73448\\Desktop\\ccc.mp4";
        long startTime = System.currentTimeMillis();
        copyByBuffer(srcPath, desPath);
        long midTime = System.currentTimeMillis();
        System.out.println("->>" + (midTime - startTime) + "ms");
        copyByFile(srcPath, desPath1);
        long endTime = System.currentTimeMillis();
        System.out.println("<<-" + (endTime - midTime) + "ms");
    }
    public static void copyByFile(String srcPath,
                                    String desPath) {
        File srcFile = new File(srcPath);
        File desFile = new File(desPath);

        FileInputStream fis = null;
        FileOutputStream fos = null;


        try {
            desFile.createNewFile();

            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(desFile);
            // BufferedInput/OutputStream 创建的时候需要有
            // 别的字节流


            int pos = 0;
            byte[] buf = new byte[1024];

            while ((pos = fis.read(buf)) != -1) {
                fos.write(buf, 0, pos);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 只需要关闭 bis 和 bos
            // 会在bis和bos的close方法中
            // 自动的关闭 fis和fos
            IOUtils.closeAll(fis, fos);
        }
    }

    public static void copyByBuffer(String srcPath,
                                    String desPath) {
        File srcFile = new File(srcPath);
        File desFile = new File(desPath);

        FileInputStream fis = null;
        FileOutputStream fos = null;

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            desFile.createNewFile();

            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(desFile);
            // BufferedInput/OutputStream 创建的时候需要有
            // 别的字节流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            int pos = 0;
            byte[] buf = new byte[1024];

            while ((pos = bis.read(buf)) != -1) {
                bos.write(buf, 0, pos);
            }
            // 在使用BufferedOutputStream的时候
            // 需要在最后 加上一句 bos.flush();
            // 无论BOS里面的数组 满没满
            // 都将里面的数据写到硬盘中
            bos.flush();



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 只需要关闭 bis 和 bos
            // 会在bis和bos的close方法中
            // 自动的关闭 fis和fos
            IOUtils.closeAll(bis, bos);
        }
    }
}
